<script lang="ts" setup>
  import type { User } from '@/types/user';
  import { onMounted, ref } from 'vue';
  import { Game } from '@/types/game';
  import { Form, Message } from '@arco-design/web-vue';
  import useTable from '@/hooks/table';
  import { getGameList, manualEnrollGame } from '@/api/game';
  import _ from 'lodash';
  import GameSignProductSelector from './game-sign-product-selector.vue';

  const props = defineProps<{
    gameInfo: Game;
  }>();

  const emit = defineEmits(['close']);

  const { list: childGameList } = useTable<Game>();

  const getChildGameData = async (parentId: string) => {
    try {
      const res = await getGameList({
        pageIndex: 1,
        pageSize: 10000,
        parentId,
        approveStates: [1],
      });
      childGameList.value = res?.data?.data?.list || [];
    } finally {
      // do nothing
    }
  };

  const saving = ref(false);
  const data = ref<{
    gameId?: string;
    productIds?: string[];
    user: Partial<User>;
  }>({
    user: {
      ageType: 1,
    },
  });
  const formRef = ref<InstanceType<typeof Form> | null>(null);

  onMounted(() => {
    if (props.gameInfo.gameType === 1 && props.gameInfo.childGameCount === 1) {
      getChildGameData(props.gameInfo.id);
    } else {
      data.value.gameId = props.gameInfo.id;
    }
  });

  const handleSubmit = async () => {
    if (formRef.value) {
      const validate = await formRef.value.validate();
      if (!validate) {
        try {
          saving.value = true;
          const enrollInfo = _.cloneDeep(data.value);
          // 教练
          if (enrollInfo.user.ageType === 3) {
            enrollInfo.user.ageType = 2;
            enrollInfo.user.userType = 2;
          } else {
            enrollInfo.user.userType = 0;
          }
          await manualEnrollGame(enrollInfo);
          Message.success('操作成功');
          emit('close', true);
        } finally {
          saving.value = false;
        }
      }
    }
  };
</script>

<template>
  <a-modal
    title="人工报名"
    :width="600"
    visible
    :ok-loading="saving"
    @cancel="emit('close', false)"
    @before-ok="handleSubmit"
  >
    <a-form ref="formRef" :model="data" layout="vertical">
      <a-divider orientation="left">会员信息</a-divider>
      <a-row :gutter="12">
        <a-col>
          <a-form-item
            label="会员类型"
            field="user.ageType"
            :rules="[{ required: true, message: '不能为空' }]"
          >
            <a-radio-group
              v-model="data.user.ageType"
              :options="[
                { label: '青少年', value: 1 },
                { label: '成人', value: 2 },
                { label: '教练', value: 3 },
              ]"
            />
          </a-form-item>
        </a-col>
        <a-col :span="16">
          <a-form-item
            label="姓名"
            field="user.nickname"
            :rules="[{ required: true, message: '不能为空' }]"
          >
            <a-input v-model="data.user.nickname" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="性别"
            field="user.sex"
            :rules="[{ required: true, message: '不能为空' }]"
          >
            <a-radio-group
              v-model="data.user.sex"
              :options="[
                { label: '男', value: 1 },
                { label: '女', value: 0 },
              ]"
            ></a-radio-group>
          </a-form-item>
        </a-col>
        <template v-if="data.user.ageType === 1">
          <a-col :span="10">
            <a-form-item
              label="证件类型"
              field="user.idType"
              :rules="[{ required: true, message: '不能为空' }]"
            >
              <a-select
                v-model="data.user.idType"
                :options="['大陆居民身份证', '护照', '台胞证', '回乡证']"
              />
            </a-form-item>
          </a-col>
          <a-col :span="14">
            <a-form-item
              label="证件号码"
              field="user.idNo"
              :rules="[{ required: true, message: '不能为空' }]"
            >
              <a-input v-model="data.user.idNo" />
            </a-form-item>
          </a-col>
        </template>
        <a-col :span="12">
          <a-form-item
            label="手机号"
            field="user.phone"
            :rules="
              data.user.ageType === 2 || data.user.ageType === 3
                ? [{ required: true, message: '不能为空' }]
                : []
            "
          >
            <a-input v-model="data.user.phone" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="近半年最佳杆数" field="user.best">
            <a-input-number v-model="data.user.best" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-divider orientation="left">
        {{
          gameInfo.gameType === 1 && gameInfo.childGameCount === 1
            ? '设置分场及费用'
            : '设置费用'
        }}
        （需确保线下已缴费）
      </a-divider>
      <a-form-item
        v-if="gameInfo.gameType === 1 && gameInfo.childGameCount === 1"
        label="分场"
        field="gameId"
        :rules="[{ required: true, message: '不能为空' }]"
      >
        <a-select
          v-model="data.gameId"
          placeholder="可输入比赛名称检索"
          allow-search
          :options="childGameList.map((i) => ({ label: i.name, value: i.id }))"
        />
      </a-form-item>

      <a-form-item
        v-if="data.gameId"
        label="费用项目"
        field="productIds"
        :rules="[{ required: true, message: '不能为空' }]"
      >
        <GameSignProductSelector
          v-model="data.productIds"
          :game-id="data.gameId"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
